package com.web.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.web.servlet.dao.DBConnect;

public class RegisterServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request,response);
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		response.setContentType("text/plain");
		response.setCharacterEncoding("utf-8");
		
		PrintWriter out = response.getWriter();
		
		String userName =request.getParameter("userName");
		String userPassword =request.getParameter("userPassword");
		String userNike =request.getParameter("userNike");
		userNike = new String(userNike.getBytes("iso-8859-1"), "utf-8");
		
		String strIp = request.getRemoteAddr();
		
		//System.out.println("userName="+userName+"   userPassword=="+userPassword+ " userNike=="+userNike);
	    
	    if(userName!=null && userPassword!=null &&userNike!=null)
	    {
	    	boolean bInsertSuccess =DBConnect.insertOneUser(userName,userPassword,userNike,strIp);
	    	if (bInsertSuccess==false)
	    	{
	    		RegisterFail(out,"用户名已经存在,请重新注册");
	    	}
	    	else
	    	{
	    		Document document = DocumentHelper.createDocument();
		    	Element rootElement = document.addElement("user");
		    	rootElement.addAttribute("st", "success");
		    	out.print(document.asXML());
	    	}
	    	
	    }
	    else
	    {
	    	RegisterFail(out,"注册信息不能为空");
	    }
		
		out.flush();
		out.close();
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}
	
	private void RegisterFail(PrintWriter out,String desc)
	{
		Document document = DocumentHelper.createDocument();
    	Element rootElement = document.addElement("user");
    	rootElement.addAttribute("st", "false");
    	rootElement.addAttribute("dc", desc);
    	out.print(document.asXML());
		
	}

}
